package com.tarena.lbs.basic.web.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.basic.web.mapper.BusinessMapper;
import com.tarena.lbs.pojo.basic.po.BusinessPO;
import com.tarena.lbs.pojo.basic.query.BusinessQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class BusinessRepository {
    @Autowired
    private BusinessMapper businessMapper;

    /**
        <select id="selectPage" resultType="BusinessPO">
            select * from lbs_business
            <where>
                <if test="businessName!= null">
                    and business_name like concat("%",#{businessName},"%"})
                </if>
            </where>
        </select>
     */
    public PageInfo<BusinessPO> getBusinessPage(BusinessQuery query) {
        //1. 拼接查询条件
        QueryWrapper<BusinessPO> wrapper = new QueryWrapper<>();
        //条件拼接的逻辑是非空就组装where clause
        //where business_name like "%%" and business_head_phone=#{} and business_status=#{}
        //and #{endTime}>create_time and #{startTime}<create_time
        if(StringUtils.isNotBlank(query.getBusinessName())){
            wrapper.like("business_name",query.getBusinessName());
        }
        if (StringUtils.isNotBlank(query.getBusinessHeadPhone())){
            wrapper.eq("business_head_phone",query.getBusinessHeadPhone());
        }
        if (query.getBusinessStatus()!=null){
            wrapper.eq("business_status",query.getBusinessStatus());
        }
        if (query.getStartingTime()!=null&&query.getEndTime()!=null){
            //比较字段 小数 大数
            wrapper.between("entry_time",query.getStartingTime(),query.getEndTime());
        }
        if (query.getBusinessId()!=null){
            wrapper.eq("id",query.getBusinessId());
        }
        //排序 sort entry_time asc desc
        wrapper.orderByDesc("entry_time");
        //2. pageHelper开启分页
        PageHelper.startPage(query.getPageNo(),query.getPageSize());
        //3. 执行sql查询 SELECT * FROM lbs_business where 拼接条件 order by entry_time limit 10;
        List<BusinessPO> pos = businessMapper.selectList(wrapper);
        //4. pageInfo封装 返回
        PageInfo<BusinessPO> poPageInfo=new PageInfo<>(pos);
        return poPageInfo;
    }


    public Long countByName(String businessName) {
        //select count(0) from lbs_business where business_name=#{businessName}
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("business_name",businessName);
        return businessMapper.selectCount(queryWrapper);
    }

    public void saveBusiness(BusinessPO poParam) {
        businessMapper.insert(poParam);
    }

    public BusinessPO getBusiness(Integer businessId) {
        return businessMapper.selectById(businessId);
    }
}
